package com.leetcode.string;

/**
 * @author Dennis Li
 * @date 2020/10/27 11:14
 */
public class MyAtoi_8 {
    
    private boolean overflow = false;

    public int myAtoi(String s) {
        if (s.equals("")) return 0;
        int num = 0, sign = 1;
        int start = 0;
        while (start < s.length() - 1 && s.charAt(start) == ' ') {
            start++;
        }
        char ch = s.charAt(start);
        if (ch == '+' || ch == '-') {
            sign = ch == '+' ? 1 : -1;
        } else if (Character.isDigit(ch)) {
            num += ch - '0';
        } else {
            return num;
        }
        for (int i = start + 1; i < s.length(); i++) {
            char c = s.charAt(i);
            if (!Character.isDigit(c)) {
                return getResult(num, sign);
            }
            num = overflow(num, c - '0') ? Integer.MAX_VALUE : num * 10 + c - '0';
        }
        return getResult(num, sign);
    }

    private int getResult(int num, int sign) {
        if (overflow && num == Integer.MAX_VALUE) {
            return sign == 1 ? num : Integer.MIN_VALUE;
        } else {
            return sign == 1 ? num : -num;
        }
    }

    private boolean overflow(int a, int b) {
        int temp = a * 10 + b;
        if (a > Integer.MAX_VALUE / 10 || a > temp) {
            overflow = true;
            return true;
        } else {
            return false;
        }
    }

}
